package com.infolab.aims.web.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.infolab.aims.GlobalConstant;
import com.infolab.aims.common.exception.NoDepartmentMemberException;
import com.infolab.aims.common.exception.StockFreezeException;
import com.infolab.aims.domain.SystemUser;

public class StockFreezeInterceptor extends HandlerInterceptorAdapter{
 
	private static final Logger logger = Logger.getLogger(StockFreezeInterceptor.class);
 
	//before the actual handler will be executed
	public boolean preHandle(HttpServletRequest request, 
		HttpServletResponse response, Object handler)
	    throws Exception {
		Map<String, String> locks = (Map<String, String>) request.getSession().getServletContext().getAttribute(GlobalConstant.GLOBAL_LOCK);
		SystemUser systemUser = (SystemUser) request.getSession().getAttribute(GlobalConstant.SESSION_CURRENT_SYSTEMUSER);
		if(systemUser.isSuperAdmin()){	
			return true;		
		}
		if(systemUser.getDepartment() != null){
			String lock = locks.get(String.valueOf(systemUser.getDepartment().getDepartmentId()));
			if(StringUtils.equalsIgnoreCase(lock, "1"))
			{
				logger.warn("Freeze !!!");
				throw new StockFreezeException();
			}
			return true;
		}else{
			logger.warn("["+ systemUser.getUserName() +"] is not in the department !!!");
			throw new NoDepartmentMemberException();
		}
	}
 
}